package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.common.manger.pojo.MangerUser;
import com.zhentao.service.MangerUserService;
import com.zhentao.mapper.MangerUserMapper;
import com.zhentao.utils.common.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
* @author 薄超轩
* @description 针对表【manger_user】的数据库操作Service实现
* @createDate 2024-09-26 14:05:15
*/
@Service
public class MangerUserServiceImpl implements MangerUserService{
    @Autowired
    private MangerUserMapper mangerUserMapper;

    @Override
    public ResponseResult maUserLogin(MangerUser mangerUser) {
        //检验参数不能登入空
        if (mangerUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据手机号查询数据
        QueryWrapper<MangerUser> wrapper=new QueryWrapper();
        wrapper.lambda().eq(MangerUser::getPhone, mangerUser.getPhone() );
        MangerUser user = mangerUserMapper.selectOne(wrapper);
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断加盐后的密码是否正确
        String password= DigestUtils.md5DigestAsHex((user.getSalt()+mangerUser.getPassword()).getBytes());
        if (!user.getPassword().equals(password)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //生成token并返回给前端
        Map<String,Object>map=new HashMap<>();
        map.put("token", AppJwtUtil.getToken(user.getId().longValue()));
        user.setSalt("");
        user.setPassword("");
        map.put("user", user);
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult findById(Integer id) {
        MangerUser user = mangerUserMapper.selectById(id);
        return ResponseResult.okResult(user);
    }

    @Override
    public ResponseResult update(MangerUser mangerUser) {
        mangerUser.setPassword(DigestUtils.md5DigestAsHex((mangerUser.getSalt()+mangerUser.getPassword()).getBytes()));
        mangerUserMapper.updateById(mangerUser);
        return ResponseResult.okResult("修改成功");
    }
}




